Masthead

Converting Files

To read a file, do conversions, and then write it back out again, we just have to add the code to write a file to our code from before that reads a file.

import csv

TheFile=open("C:\\Users\\Jim\\Desktop\\GSP 318\\Lab07/all_hour.csv","r") # open the file for reading (thus the "r")

TheOutputFile=open("C:\\Users\\Jim\\Desktop\\GSP 318\\Lab07/output.csv","w") # open the output file for writing

TheOutputFile.write("Column1,Column2\n") # output the header line

TheCSVReader=csv.reader(TheFile) # create an object to read the file as a CSV file

NumRows=0
for TheRow in TheCSVReader: # Loop on each line in the file 
	if (NumRows>0): # skip the header line

		TheDateTimeString=TheRow[0] # get the datetime string
		print(TheDateTimeString) # print the string for debugging
	
		TheLatitude = TheRow[1]
		
		TheOutputFile.write(TheDateTimeString+","+TheLatitude+"\n")
	NumRows+=1

TheFile.close()

print("Read "+format(NumRows)+" rows from the file")

 

Additional Resources

Python Documentation: String functions

Python Documentation: Defining Functions

 

© Copyright 2018 HSU - All rights reserved.